package com.ruoyi.system.kysh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.kysh.entity.TableInf;
import com.ruoyi.system.kysh.entity.TeamClassInf;
import com.ruoyi.system.kysh.entity.dto.TeamClassInfsDto;
import com.ruoyi.system.kysh.mapper.AcceptInfMapper;
import com.ruoyi.system.kysh.mapper.TableInfMapper;
import com.ruoyi.system.kysh.mapper.TeamClassInfMapper;
import com.ruoyi.system.kysh.service.AcceptInfService;
import com.ruoyi.system.kysh.service.TeamClassInfService;
import com.ruoyi.system.kysh.utils.MyTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeamClassInfServiceImpl implements TeamClassInfService {

    @Autowired
    private TeamClassInfMapper teamClassInfMapper;

    @Autowired
    private TableInfMapper tableInfMapper;

    @Autowired
    private AcceptInfMapper acceptInfMapper;

    @Override
    public List<TeamClassInf> selectByDeptAndNameAndPostAndPage(String deptName,String parentName, String nickName, String postName, int page, int pageSize) {
        Long deptId=teamClassInfMapper.selectDeptIdByName(deptName,parentName);
        List<Long> userId;
        List<Long> postId;

        //姓名为空默认查找所有
        if(nickName==null||"".equals(nickName)){
            userId=teamClassInfMapper.selectAllUserId();
        }else{
            userId=teamClassInfMapper.selectUserIdByNickName(nickName);
        }

        //职位默认为所有
        if(postName==null||"".equals(postName)){
            postId=teamClassInfMapper.selectAllPostId();
        }else {
            postId=teamClassInfMapper.selectPostIdByPostName(postName);
        }

        //分页查询
        int firstIndex=(page-1)*pageSize;
        List<TeamClassInf> teamClassInfs = teamClassInfMapper
                .selectByIdsAndPages(deptId, userId, postId, firstIndex, pageSize);

        //对查找到的集合进行信息补充
        return teamClassInfs.stream().peek((it) -> {
            LambdaQueryWrapper<TableInf> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TableInf::getDeptId, it.getParentId());
            it.setParentDeptName(tableInfMapper.selectOne(lambdaQueryWrapper).getDeptName());//查找该父部门
            it.setDeptRank(tableInfMapper.getDeptRank(it.getParentId()).split(",").length);//设置部门层级
        }).collect(Collectors.toList());
    }

    @Override
    public TeamClassInfsDto showNewClassInf(Long deptId,int page, int pageSize) {
        if(deptId!=null && deptId>=10000){
            deptId=teamClassInfMapper.selectParentIdByDeptId(deptId);
        }else{
            deptId=null;
        }
        List<TeamClassInf> teamClassInfs=teamClassInfMapper.selectByAllPostIds(deptId);

        List<Long> userId=new ArrayList<>();
        teamClassInfs.forEach((it)->{
            int length = tableInfMapper.getDeptRank(it.getParentId()).split(",").length;//部门层级
            if(length<=2){
                userId.add(it.getUserId());
            }
        });

        if(userId.isEmpty()){
            return null;
        }

        int firstIndex=(page-1)*pageSize;
        int endIndex=firstIndex+pageSize;
        List<TeamClassInf> teamClassInfs1 = teamClassInfMapper.selectNewClassInfAll(userId);

        TeamClassInfsDto teamClassInfsDto = new TeamClassInfsDto();
        if(endIndex>teamClassInfs1.size()){
            endIndex=teamClassInfs1.size();
        }

        List<TeamClassInf> teamClassInfs2 = teamClassInfs1.subList(firstIndex, endIndex);
        teamClassInfsDto.setTeamClassInfList(teamClassInfs2);
        teamClassInfsDto.setTotal(teamClassInfs1.size());
        teamClassInfsDto.setSize(teamClassInfs2.size());


        return teamClassInfsDto;
    }

    @Override
    public String isSame(TeamClassInf[] teamClassInfs) {
        Set<String> s=new HashSet<>();
        for(TeamClassInf teamClassInf:teamClassInfs){
            s.add(teamClassInf.getDeptName());
        }
        //上级部门是否不唯一
        if(s.size()==1){
            return teamClassInfs[0].getDeptName();//返回当前所在部门
        }
        return null;
    }

    @Override
    public void makeEmpolyInDept(TeamClassInf[] teamClassInfs, String deptName,String parentDeptName) {
        Long deptId=teamClassInfMapper.selectDeptIdByName(deptName,parentDeptName);
        for(TeamClassInf teamClassInf:teamClassInfs){
            teamClassInfMapper.updateClassInfInDept(teamClassInf.getUserId(),deptId, MyTimeUtil.nowTime());
        }

    }

    @Override
    public void deleteByUserIdAndParentId(Long userId, Long parentId) {
        teamClassInfMapper.deleteByUserAndParentId(userId,parentId);
    }

    @Override
    public String findMorByDept(String deptName, String parentName) {
        Long deptId = teamClassInfMapper.selectDeptIdByName(deptName, parentName);
        List<Long> userIds=teamClassInfMapper.selectUserIdByDeptId(deptId);
        String name=teamClassInfMapper.selectUserNameIsMor(userIds);
        if(name==null||"".equals(name)){
            return null;
        }
        return name;
    }

    @Override
    public String findAccByDept(String deptName, String parentName) {
        Long deptId = teamClassInfMapper.selectDeptIdByName(deptName, parentName);
        List<Long> userIds=teamClassInfMapper.selectUserIdByDeptId(deptId);
        String name=teamClassInfMapper.selectUserNameIsAcc(userIds);
        if(name==null||"".equals(name)){
            return null;
        }
        return name;
    }

    @Override
    public List<TeamClassInf> getUserInfNotSelect(String deptName,String parentName) {
        Long deptId = teamClassInfMapper.selectDeptIdByName(deptName, parentName);
        List<String> userIdByDeptId=teamClassInfMapper.selectExUserIdByDeptId(deptId);

        userIdByDeptId=userIdByDeptId.stream().distinct().collect(Collectors.toList());

        StringBuffer stringBuffer=new StringBuffer();
        userIdByDeptId.forEach((id)->{
            stringBuffer.append(id);
            stringBuffer.append(",");
        });
        String selectedUserIdString=stringBuffer.toString();
        List<Long> selectedUserIds=new ArrayList<>();
        if(!"".equals(selectedUserIdString)){
            ArrayList<String> userIdByString = new ArrayList<>(Arrays.asList(selectedUserIdString.split(",")));
            for(String s:userIdByString){
                if(s!=null && !"".equals(s)){
                    selectedUserIds.add(Long.parseLong(s));
                }
            }
        }

        List<Long> userIds = teamClassInfMapper.selectUserIdByDeptId(deptId);
        List<Long> notSelectId=userIds.stream().map((it)->{
            boolean contains = selectedUserIds.contains(it);
            if(contains){
                return null;
            }else{
                return it;
            }
        }).collect(Collectors.toList());
        return teamClassInfMapper.selectNewClassInf(notSelectId,0,100);
    }

    @Override
    public void saveUsersByDeptId(Long taskId, String deptName, String parentName, List<Long> userId) {
        Long deptId = teamClassInfMapper.selectDeptIdByName(deptName, parentName);
        StringBuffer stringBuffer=new StringBuffer();

        userId.forEach((id)->{
            stringBuffer.append(id);
            stringBuffer.append(",");
        });

        String userIds=stringBuffer.substring(0,userId.size()*2-1);

        teamClassInfMapper.saveUserIdsAndDeptByTask(taskId,deptId,userIds);
    }

    @Override
    public List<TeamClassInf> getUserInfByTaskId(Long taskId) {
        String userIds=teamClassInfMapper.selectUserIdsByTaskId(taskId);
        List<Long> userId = Arrays.stream(userIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<TeamClassInf> teamClassInfs=new ArrayList<>();
        userId.forEach((id)->{
            TeamClassInf teamClassInf=new TeamClassInf();
            teamClassInf.setUserId(id);
            teamClassInf.setNickName(teamClassInfMapper.selectNickNameByUserId(id));
            teamClassInf.setPostName(teamClassInfMapper.selectPostNameByUserId(id));
            teamClassInfs.add(teamClassInf);
        });
        return teamClassInfs;
    }

    @Override
    public TeamClassInfsDto selectByDeptIdAndNameAndPostAndPage(Long deptId, String nickName, String postName, int page, int pageSize) {
        List<Long> userId;
        List<Long> postId;

        //姓名为空默认查找所有
        if(nickName==null||"".equals(nickName)){
            userId=teamClassInfMapper.selectAllUserId();
        }else{
            userId=teamClassInfMapper.selectUserIdByNickName(nickName);
        }

        //职位默认为所有
        if(postName==null||"".equals(postName)){
            postId=teamClassInfMapper.selectAllPostId();
        }else {
            postId=teamClassInfMapper.selectPostIdByPostName(postName);
        }

        //分页查询
        int firstIndex=(page-1)*pageSize;
        int endIndex=firstIndex+pageSize;

        List<TeamClassInf> teamClassInfs = teamClassInfMapper
                .selectByIdsAndPagesAll(deptId, userId, postId);

        TeamClassInfsDto teamClassInfsDto = new TeamClassInfsDto();

        if(endIndex>teamClassInfs.size()){
            endIndex=teamClassInfs.size();
        }
        List<TeamClassInf> teamClassInfs1 = teamClassInfs.subList(firstIndex, endIndex);

        teamClassInfs1=teamClassInfs1.stream().peek((it) -> {
            LambdaQueryWrapper<TableInf> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TableInf::getDeptId, it.getParentId());
            it.setParentDeptName(tableInfMapper.selectOne(lambdaQueryWrapper).getDeptName());//查找该父部门
            it.setDeptRank(tableInfMapper.getDeptRank(it.getParentId()).split(",").length);//设置部门层级

            it.setMorName(findMorByDeptId(deptId));

        }).collect(Collectors.toList());

        teamClassInfsDto.setTeamClassInfList(teamClassInfs1);
        teamClassInfsDto.setSize(teamClassInfs1.size());
        teamClassInfsDto.setTotal(teamClassInfs.size());

        //对查找到的集合进行信息补充
        return teamClassInfsDto;
    }

    private String findMorByDeptId(Long deptId) {
        if(deptId<10000){
            return null;
        }
        List<Long> userIds=teamClassInfMapper.selectUserIdByDeptId(deptId);
        String name=teamClassInfMapper.selectUserNameIsMor(userIds);
        if(name==null||"".equals(name)){
            return null;
        }
        return name;
    }

    @Override
    public void makeEmpolyInDeptId(List<TeamClassInf> teamClassInfs, Long deptId) {
        for(TeamClassInf teamClassInf:teamClassInfs){
            teamClassInfMapper.updateClassInfInDept(teamClassInf.getUserId(),deptId, MyTimeUtil.nowTime());
        }
    }

    @Override
    public boolean morIsExist(TeamClassInf teamClassInf) {
        String name=findMorByDept(teamClassInf.getDeptName(),teamClassInf.getParentDeptName());
        if(name!=null){
            return name.equals(teamClassInf.getPostName());
        }
        return false;
    }

    @Override
    public void updateClassInf(TeamClassInf teamClassInf) {
        Long deptId = teamClassInfMapper.selectDeptIdByName(teamClassInf.getDeptName(),teamClassInf.getParentDeptName());
        List<Long> postId=teamClassInfMapper.selectPostIdByPostName(teamClassInf.getPostName());

        teamClassInfMapper.updateClassInf(teamClassInf.getUserId(),postId.get(0),deptId,MyTimeUtil.nowTime());
    }


}
